<template>
  <div class="c-upload-image">
    <div class="justify-left">
      <el-upload
        v-loading="loadingButton"
        :disabled="disabled"
        :action="VUE_APP_API + fileUpload"
        :on-change="filechange"
        :auto-upload="false"
        :show-file-list="false"
        class="avatar-uploader"
        accept="image/*"
      >
        <div slot="tip" class="el-upload__tip" style="margin: 0">{{ tip }}</div>
        <el-image
          v-if="value"
          :src="imgsrc+'?x-oss-process=image/resize,w_118'"
          class="avatar"
          fit="cover"
          accept="image/*"
        />
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <div
        v-if="!hasCropper && value"
        slot="tip"
        class="text-center pointer"
        style="color: #409eff; margin-top: -40px"
        @click="lookPicDialog = true"
      >
        点击预览原图
      </div>
    </div>
    <el-dialog
      title="查看图片"
      :width="'700px'"
      :modal="false"
      :visible.sync="lookPicDialog"
    >
      <img
        style="
          display: block;
          max-width: 600px;
          min-width: 400px;
          margin: 0 auto;
        "
        :src="imgsrc"
      >
    </el-dialog>
    <el-dialog
      title="裁剪"
      :visible.sync="dialogValue"
      width="900px"
      center
      :close-on-click-modal="false"
      :show-close="false"
      :append-to-body="true"
    >
      <div
        style="
          width: 850px;
          height: 422px;
          border: dashed #cacaca 1px;
          text-align: center;
        "
      >
        <div class="cropper" style="max-width: 100%; height: 100%">
          <vueCropper
            ref="cropper"
            :img="imageUrl"
            :output-size="option.size"
            :output-type="option.outputType"
            :info="true"
            :full="option.full"
            :can-move="option.canMove"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :auto-crop="option.autoCrop"
            :auto-crop-width="autoCropWidth"
            :auto-crop-height="autoCropHeight"
            :fixed-box="option.fixedBox"
            :fixed="option.fixed"
            :fixed-number="fixedNumber"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-loading="loadingButton" @click="closeImg">取 消</el-button>
        <el-button
          v-loading="loadingButton"
          type="primary"
          @click="uploadImg()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
const VUE_APP_API = process.env.VUE_APP_API
const VUE_APP_FILE = process.env.VUE_APP_FILE
import { VueCropper } from 'vue-cropper'
import { upload, fileUpload } from '@/api/upload'
export default {
  components: {
    VueCropper
  },
  props: {
    hasFileUrl: { type: Boolean, default: true },
    disabled: { type: Boolean, default: false },
    // fileUrl: { type: String }, // 图片上传地址   this.$api.sys.file,

    value: { type: [String, Number] },
    fixedNumber: { type: Array, default: () => [16, 9] }, // 截图框比例  (默认:[1:1])

    autoCropWidth: { type: String, default: '1960' }, // 默认生成截图框宽度  (无数值默认:80%)
    autoCropHeight: { type: String, default: '1080' }, // 默认生成截图框高度  (无数值默认:80%)
    fixedBox: { type: Boolean, default: false }, // 固定截图框大小 不允许改变  (默认:false)
    tip: {
      type: String,
      default: '仅支持jpg/png格式文件，且文件大小不超过1M'
    },

    fileSize: {
      // 1MB
      type: [String, Number],
      default: 0.09765625
    },
    width: {
      type: Number,
      default: 300
    },
    height: {
      type: Number,
      default: 300
    },
    group: { type: String, default: 'avatar' },
    tenantId: { type: [String, Number], default: '' },
    hasCropper: {
      // 是否需要裁剪
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      imageUrl: '',
      VUE_APP_API,
      VUE_APP_FILE,
      fileUpload, // 图片上传地址
      lookPicDialog: false,
      /* 裁剪面板 */
      dialogValue: false,
      loadingButton: false,
      option: {
        outputSize: 1, // 裁剪生成图片的质量  (默认:1)
        full: false, // 是否输出原图比例的截图 选true生成的图片会非常大  (默认:false)
        outputType: 'png', // 裁剪生成图片的格式  (默认:jpg)
        canMove: false, // 上传图片是否可以移动  (默认:true)
        original: false, // 上传图片按照原始比例渲染  (默认:false)
        canMoveBox: true, // 截图框能否拖动  (默认:true)
        autoCrop: true, // 是否默认生成截图框  (默认:false)
        fixedBox: false, // 固定截图框大小 不允许改变  (默认:false)
        fixed: false, // 是否开启截图框宽高固定比例  (默认:true)
        enlarge: 1
      }
    }
  },
  computed: {
    imgsrc() {
      const src = this.value || ''
      if (src && this.hasFileUrl) {
        return src.indexOf('https:') > -1 ? src : VUE_APP_FILE + src
      } else if (!this.hasFileUrl) {
        return src
      } else {
        return ''
      }
    }
  },
  created() {
  },
  methods: {
    // 图片上传逻辑
    uploadFunc(fileToBlob) {
      var file = new File([fileToBlob], 'file.png')
      var formdata = new FormData()
      formdata.append('file', file)
      upload(formdata)
        .then(res => {
          this.$emit('input', res.data)
          this.$emit('changeInput', res.data)
          this.loadingButton = false
          this.dialogValue = false
        })
        .catch(() => {
          this.dialogValue = false
          this.loadingButton = false
        })
    },
    /* 上传文件改变钩子,   单文件上传时用于裁剪 */
    filechange(file, fileList) {
      const isLtMb = file.size / 1024 / 1024 < this.fileSize
      const isLtKb = (this.fileSize * 1024).toFixed(2)
      if (!isLtMb) {
        this.$message.error(`上传图片大小不能超过${isLtKb}KB!`)
        return
      }
      const img = new Image()
      const _self = this
      const _URL = window.URL || window.webkitURL
      img.src = _URL.createObjectURL(file.raw)
      img.onload = function() {
        if (img.width > _self.width || img.height > _self.height) {
          _self.$message.error(
            `上传的图片最大尺寸为${_self.width}*${_self.height}`
          )
          return
        }
        if (!_self.hasCropper) {
          // 如果不需要裁剪
          _self.loadingButton = true
          _self.uploadFunc(file.raw)
          return
        }
        const url = URL.createObjectURL(file.raw)
        _self.imageUrl = url
        _self.dialogValue = true
      }
    },
    uploadImg() {
      // 将剪裁好的图片回传给父组件
      this.loadingButton = true
      this.$refs.cropper.getCropBlob(data => {
        this.uploadFunc(data)
      })
    },

    closeImg() {
      this.dialogValue = false
      this.loadingButton = false
    },

    close() {
      this.$emit('input', false)
    },
    header() {
      return {
        Authorization: 'Bearer ' + this.$Cookies.get('token')
      }
    }
  }
}
</script>
<style lang="scss">
.c-upload-image {
  .avatar-uploader {
    .el-icon-s-custom {
      font-size: 100px;
    }
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    display: block;
  }
}
</style>
